from PyQt5.QtWidgets import (QDialog, QVBoxLayout, QHBoxLayout, QTabWidget,
                                    QWidget, QLabel, QComboBox, QCheckBox,
                                    QPushButton, QSpinBox, QLineEdit, QFormLayout,
                                    QGroupBox, QDialogButtonBox)
from PyQt5.QtCore import Qt
from ..utils.config import config
from ..utils.themes import get_available_themes
from ..utils.logger import logger

class SettingsDialog(QDialog):
    def __init__(self, parent=None):
        super().__init__(parent)
        self.init_ui()
        self.load_settings()

    def init_ui(self):
        """初始化界面"""
        self.setWindowTitle("设置")
        self.setMinimumWidth(400)
        
        # 主布局
        layout = QVBoxLayout(self)
        
        # 创建选项卡
        tab_widget = QTabWidget()
        
        # 添加常规设置选项卡
        general_tab = self.create_general_tab()
        tab_widget.addTab(general_tab, "常规")
        
        # 添加视频设置选项卡
        video_tab = self.create_video_tab()
        tab_widget.addTab(video_tab, "视频")
        
        # 添加平台设置选项卡
        platform_tab = self.create_platform_tab()
        tab_widget.addTab(platform_tab, "平台")
        
        layout.addWidget(tab_widget)
        
        # 添加确定和取消按钮
        button_box = QDialogButtonBox(
            QDialogButtonBox.Ok | QDialogButtonBox.Cancel
        )
        button_box.accepted.connect(self.accept)
        button_box.rejected.connect(self.reject)
        layout.addWidget(button_box)

    def create_general_tab(self) -> QWidget:
        """创建常规设置选项卡"""
        widget = QWidget()
        layout = QVBoxLayout(widget)
        
        # 界面设置组
        ui_group = QGroupBox("界面设置")
        ui_layout = QFormLayout()
        
        # 主题选择
        self.theme_combo = QComboBox()
        themes = get_available_themes()
        for theme_id, theme_name in themes.items():
            self.theme_combo.addItem(theme_name, theme_id)
        ui_layout.addRow("主题:", self.theme_combo)
        
        # 语言选择
        self.language_combo = QComboBox()
        self.language_combo.addItem("简体中文", "zh_CN")
        self.language_combo.addItem("English", "en_US")
        ui_layout.addRow("语言:", self.language_combo)
        
        ui_group.setLayout(ui_layout)
        layout.addWidget(ui_group)
        
        # 通知设置组
        notify_group = QGroupBox("通知设置")
        notify_layout = QVBoxLayout()
        
        self.show_notifications_cb = QCheckBox("显示系统通知")
        notify_layout.addWidget(self.show_notifications_cb)
        
        self.minimize_to_tray_cb = QCheckBox("最小化到系统托盘")
        notify_layout.addWidget(self.minimize_to_tray_cb)
        
        notify_group.setLayout(notify_layout)
        layout.addWidget(notify_group)
        
        # 添加弹性空间
        layout.addStretch()
        
        return widget

    def create_video_tab(self) -> QWidget:
        """创建视频设置选项卡"""
        widget = QWidget()
        layout = QFormLayout(widget)
        
        # 视频格式
        self.format_combo = QComboBox()
        self.format_combo.addItems(['mp4', 'avi', 'mov', 'wmv'])
        layout.addRow("默认格式:", self.format_combo)
        
        # 帧率设置
        self.fps_spin = QSpinBox()
        self.fps_spin.setRange(15, 60)
        self.fps_spin.setValue(30)
        layout.addRow("帧率:", self.fps_spin)
        
        # 录制音频
        self.record_audio_cb = QCheckBox()
        layout.addRow("录制音频:", self.record_audio_cb)
        
        # 视频目录
        self.video_dir_edit = QLineEdit()
        self.video_dir_edit.setReadOnly(True)
        browse_btn = QPushButton("浏览...")
        browse_btn.clicked.connect(self.browse_video_directory)
        
        dir_layout = QHBoxLayout()
        dir_layout.addWidget(self.video_dir_edit)
        dir_layout.addWidget(browse_btn)
        layout.addRow("视频目录:", dir_layout)
        
        return widget

    def create_platform_tab(self) -> QWidget:
        """创建平台设置选项卡"""
        widget = QWidget()
        layout = QVBoxLayout(widget)
        
        # 抖音设置组
        douyin_group = QGroupBox("抖音")
        douyin_layout = QVBoxLayout()
        self.douyin_enabled_cb = QCheckBox("启用")
        douyin_layout.addWidget(self.douyin_enabled_cb)
        douyin_group.setLayout(douyin_layout)
        layout.addWidget(douyin_group)
        
        # B站设置组
        bilibili_group = QGroupBox("B站")
        bilibili_layout = QVBoxLayout()
        self.bilibili_enabled_cb = QCheckBox("启用")
        bilibili_layout.addWidget(self.bilibili_enabled_cb)
        bilibili_group.setLayout(bilibili_layout)
        layout.addWidget(bilibili_group)
        
        # 小红书设置组
        xiaohongshu_group = QGroupBox("小红书")
        xiaohongshu_layout = QVBoxLayout()
        self.xiaohongshu_enabled_cb = QCheckBox("启用")
        xiaohongshu_layout.addWidget(self.xiaohongshu_enabled_cb)
        xiaohongshu_group.setLayout(xiaohongshu_layout)
        layout.addWidget(xiaohongshu_group)
        
        # 添加弹性空间
        layout.addStretch()
        
        return widget

    def browse_video_directory(self):
        """浏览视频目录"""
        from PyQt5.QtWidgets import QFileDialog
        directory = QFileDialog.getExistingDirectory(
            self,
            "选择视频目录",
            self.video_dir_edit.text(),
            QFileDialog.ShowDirsOnly | QFileDialog.DontResolveSymlinks
        )
        if directory:
            self.video_dir_edit.setText(directory)

    def load_settings(self):
        """加载设置"""
        try:
            # 加载界面设置
            theme = config.get('ui.theme', 'light')
            index = self.theme_combo.findData(theme)
            if index >= 0:
                self.theme_combo.setCurrentIndex(index)
            
            language = config.get('ui.language', 'zh_CN')
            index = self.language_combo.findData(language)
            if index >= 0:
                self.language_combo.setCurrentIndex(index)
            
            # 加载通知设置
            self.show_notifications_cb.setChecked(
                config.get('ui.show_notifications', True)
            )
            self.minimize_to_tray_cb.setChecked(
                config.get('ui.minimize_to_tray', True)
            )
            
            # 加载视频设置
            self.format_combo.setCurrentText(
                config.get('video.format', 'mp4')
            )
            self.fps_spin.setValue(
                config.get('video.fps', 30)
            )
            self.record_audio_cb.setChecked(
                config.get('video.record_audio', True)
            )
            self.video_dir_edit.setText(
                config.get('video.directory', 'videos')
            )
            
            # 加载平台设置
            self.douyin_enabled_cb.setChecked(
                config.get('platforms.douyin.enabled', False)
            )
            self.bilibili_enabled_cb.setChecked(
                config.get('platforms.bilibili.enabled', False)
            )
            self.xiaohongshu_enabled_cb.setChecked(
                config.get('platforms.xiaohongshu.enabled', False)
            )
            
        except Exception as e:
            logger.error(f"加载设置失败: {str(e)}")

    def accept(self):
        """保存设置"""
        try:
            # 保存界面设置
            config.set('ui.theme', self.theme_combo.currentData())
            config.set('ui.language', self.language_combo.currentData())
            config.set('ui.show_notifications', self.show_notifications_cb.isChecked())
            config.set('ui.minimize_to_tray', self.minimize_to_tray_cb.isChecked())
            
            # 保存视频设置
            config.set('video.format', self.format_combo.currentText())
            config.set('video.fps', self.fps_spin.value())
            config.set('video.record_audio', self.record_audio_cb.isChecked())
            config.set('video.directory', self.video_dir_edit.text())
            
            # 保存平台设置
            config.set('platforms.douyin.enabled', self.douyin_enabled_cb.isChecked())
            config.set('platforms.bilibili.enabled', self.bilibili_enabled_cb.isChecked())
            config.set('platforms.xiaohongshu.enabled', self.xiaohongshu_enabled_cb.isChecked())
            
            logger.info("设置已保存")
            super().accept()
            
        except Exception as e:
            logger.error(f"保存设置失败: {str(e)}")
            from PyQt5.QtWidgets import QMessageBox
            QMessageBox.critical(self, "错误", f"保存设置失败: {str(e)}")
